package com.emit.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.emit.dao.UserMapper;
import com.emit.domain.SysUser;
import com.emit.domain.SysUserExample;
import com.emit.exception.BizException;
import com.emit.form.UserForm;
import com.emit.service.UserService;
import com.emit.utils.JwtUtils;
import com.emit.utils.Md5Utils;
import com.emit.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wanglongquan
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public UserVO login(UserForm userFrom) {
        if (StringUtils.isEmpty(userFrom.getUsername()) || StringUtils.isEmpty(userFrom.getPassword())) {
            throw new BizException("A00001","用户名和密码不能为空");
        }
        //反参对象
        UserVO userVO = new UserVO();

        //密码加密，查找该用户在数据库里存在不存在
        SysUserExample sysUserExample = new SysUserExample();
        sysUserExample.createCriteria().andUsernameEqualTo(userFrom.getUsername())
                .andPasswordEqualTo(new Md5Utils().MD5(userFrom.getPassword()));
        List<SysUser> sysUsers = userMapper.selectByExample(sysUserExample);

        if (CollectionUtil.isEmpty(sysUsers)) {
            throw new BizException("A00002","用户名或密码错误");
        }

        //返回数据内容
        SysUser sysUser = sysUsers.get(0);
        return userVO;
    }

    @Override
    public UserVO registered(UserForm userFrom) {
        if (StringUtils.isEmpty(userFrom.getUsername()) || StringUtils.isEmpty(userFrom.getPassword())) {
            throw new BizException("用户名和密码不能为空");
        }
        //反参对象
        UserVO userVO = new UserVO();
        SysUser sysUser = new SysUser();
        //密码加密
        SysUserExample sysUserExample = new SysUserExample();
        sysUser.setPassword(new Md5Utils().MD5(userFrom.getPassword()));
        BeanUtils.copyProperties(userFrom, sysUser);
        return null;
    }

    @Override
    public UserVO findUserByUsername(String username) {
        UserVO userVO=new UserVO();
        SysUserExample sysUserExample = new SysUserExample();
        sysUserExample.createCriteria().andUsernameEqualTo(username);
        SysUser sysUser = userMapper.selectByExample(sysUserExample).get(0);
        sysUser.setPassword(null);
        BeanUtils.copyProperties(sysUser,userVO);
        return userVO;
    }
}
